// 系统分页项（系统列表表格）
export interface SystemPageItem {
  status: string; // "faulty" | "offline" | "normal" | "standby"
  systemId: string; // 系统ID
  systemName: string; // 系统名称
  country: string; // 国家/地区
  address: string; // 地址
  statusColor?: string; // 颜色值（可选）
}

// 系统统计数据接口
interface SystemStatistics {
  normalCount: number; // 正常系统数量
  faultCount: number; // 故障系统数量
  offlineCount: number; // 离线系统数量
  standbyCount: number; // 待机系统数量
  totalGeneration: number; // 总发电量
  unit: string; // 单位
}

// 系统状态数据接口
interface SystemStatus {
  systemStatistics: {
    updateTime: string; // 更新时间 "2024-06-18T18:00:00Z"
    solar: {
      totalGeneration: number; // 总发电量 2331.09
      unit: string; // 单位 "kW"
    };
  };
  battery: {
    energyCharged: number; // 充电量 231.09
    energyDischarged: number; // 放电量 271.19
    unit: string; // 单位 "kW"
  };
  grid: {
    export: number; // 导出电量 2331.09
    import: number; // 导入电量 231.09
    unit: string; // 单位 "kW"
    netFlow: number; // 净流量
  };
  home: {
    consumption: number; // 消耗量
    unit: string; // 单位
  };
  message: string; // 消息
}

// 查询参数接口
interface QueryParams {
  page?: number; // 页码
  limit?: number; // 每页条数
  systemName?: string; // 系统名称（搜索条件）
  status?: string; // 状态筛选
  countryRegion?: string; // 国家/地区筛选
}

// API响应数据结构 - 根据实际API返回修正
interface ApiResponse<T> {
  code: number; // 响应码，0表示成功
  msg: string; // 响应消息
  data: {
    list: T[]; // 数据列表
    total: number; // 总条数
  };
}

// 系统状态API响应
interface SystemStatusResponse {
  code: number;
  msg: string;
  data: SystemStatus;
}

// 系统统计API响应
interface SystemStatisticsResponse {
  code: number;
  msg: string;
  data: SystemStatistics;
}

import { systemApi, systemAppApi } from "@/api/business";
import { IObject } from "@/types/interface";

// 获取系统分页列表（真实 API）
export const getSystemList = async (
  params: QueryParams
): Promise<{ list: SystemPageItem[]; totalCount: number }> => {
  try {
    // 改为调用 App 端系统列表接口，兼容后端分页字段名
    const appParams: IObject = {
      pageNum: params.page ?? 1,
      pageSize: params.limit ?? 10
    } as any;
    const resp: any = await systemAppApi.getList(appParams as IObject);
    // 兼容多种成功标识
    const success = resp?.code === 0 || resp?.code === 200 || resp?.success === true;
    if (!success) return { list: [], totalCount: 0 };

    // 兼容多种列表字段（包含 data.page.records）
    const rawList: any = Array.isArray(resp?.data)
      ? resp.data
      : resp?.data?.records ||
        resp?.data?.list ||
        resp?.data?.items ||
        resp?.data?.systems ||
        resp?.data?.page?.records || [];

    // 地址解析：lngLat 可能是对象或字符串
    const parseAddress = (val: any): string => {
      if (!val) return "";
      try {
        // 如果是字符串包着JSON
        const maybe = typeof val === "string" ? JSON.parse(val) : val;
        if (maybe && typeof maybe === "object" && maybe.local) return String(maybe.local);
      } catch (_) {
        // 忽略解析错误
      }
      return String(val?.local ?? "");
    };

    const list = (rawList || []).map((x: any) => ({
      status: String(x.status ?? ""),
      // ID：优先 hemsId / deviceKey，其次后端可能的 id / systemId
      systemId: String(x.hemsId ?? x.deviceKey ?? x.systemId ?? x.id ?? ""),
      // 透传真实标识，供详情页使用
      hemsId: x.hemsId ?? x.hemsID ?? undefined,
      deviceKey: x.deviceKey ?? x.sn ?? x.key ?? undefined,
      // 名称：兼容 name/company/systemName 等
      systemName: String(x.name ?? x.systemName ?? x.company ?? x.client ?? x.title ?? ""),
      // 地区：zone/region/countryRegion/country
      country: String(x.zone ?? x.region ?? x.countryRegion ?? x.country ?? ""),
      // 地址：优先 lngLat.local（对象或字符串），其次 address/location
      address: String(
        parseAddress(x.lngLat ?? x.IngLat) || x.address || x.location || ""
      ),
      statusColor: x.statusColor
    })) as SystemPageItem[];

    const total =
      (typeof resp?.data?.total === "number" && resp.data.total) ||
      (typeof resp?.data?.count === "number" && resp.data.count) ||
      (typeof resp?.data?.page?.total === "number" && resp.data.page.total) ||
      list.length;
    return { list, totalCount: total };
  } catch (error) {
    console.error("获取系统分页列表错误:", error);
    return { list: [], totalCount: 0 };
  }
};


export const getOverviewAccountList = async (params: {
  page: number;
  limit: number;
}): Promise<{ list: any[]; totalCount: number }> => {
  try {
    // 概览页列表也切到 App 端
    const resp: any = await systemAppApi.getList(params as unknown as IObject);
    const success = resp?.code === 0 || resp?.code === 200 || resp?.success === true;
    if (success) {
      const list = Array.isArray(resp?.data) ? resp.data : (resp?.data?.list || resp?.data?.records || []);
      const total = (resp?.data?.total ?? resp?.data?.count ?? list.length) as number;
      return { list, totalCount: total };
    }
    return { list: [], totalCount: 0 };
  } catch (e) {
    console.error("获取系统分页列表失败:", e);
    return { list: [], totalCount: 0 };
  }
};

// 获取系统状态统计
export const getSystemStatus = async (): Promise<{
  success: boolean;
  data?: { normalCount: number; faultCount: number; offlineCount: number; standbyCount: number };
  message?: string;
}> => {
  try {
    // 仅走 App 端：从系统列表统计字段转换
    const params: IObject = { pageNum: 1, pageSize: 1 } as any;
    const appResp: any = await systemAppApi.getList(params);
    const ok = appResp?.code === 0 || appResp?.code === 200 || appResp?.success === true;
    if (!ok) return { success: false, message: appResp?.msg || "获取系统状态失败" };
    const d = appResp?.data || {};
    return {
      success: true,
      data: {
        normalCount: Number(d.normal ?? 0),
        faultCount: Number(d.fault ?? 0),
        offlineCount: Number(d.offline ?? 0),
        standbyCount: Number(d.standBy ?? d.standby ?? 0)
      }
    };
  } catch (error) {
    console.error("获取系统状态错误:", error);
    return { success: false, message: "获取系统状态失败" };
  }
};

// 获取系统统计数据
export const getSystemStatistics = async (): Promise<{
  success: boolean;
  data?: any; // 返回 data.systemStatistics 对象
  message?: string;
}> => {
  try {
    // 使用 App 端: GET /installer/web/energy
    // 按文档需要 query: current, size
    const { systemAppApi } = await import("@/api/business");
    const resp: any = await systemAppApi.getEnergyStats({ current: 1, size: 1 });
    const ok = resp?.code === 0 || resp?.code === 200 || resp?.success === true;
    if (!ok || !resp?.data) {
      return { success: false, message: resp?.msg || "获取系统统计失败" };
    }
    const d: any = resp.data;
    const mapped = {
      updateTime: d.updateTime || "",
      solar: { totalGeneration: Number(d.solar ?? 0) },
      home: { consumption: Number(d.outputToHome ?? 0) },
      grid: {
        export: Number(d.outputToGrid ?? 0),
        import: Number(d.gridInput ?? 0)
      },
      battery: {
        energyCharged: Number(d.batteryInput ?? 0),
        energyDischarged: Number(d.batteryOutput ?? 0)
      }
    };
    return { success: true, data: mapped };
  } catch (error) {
    console.error("获取系统统计错误:", error);
    return { success: false, message: "获取系统统计失败" };
  }
};
